<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="打印尺寸" prop="printSize">
        <el-input
          v-model="queryParams.printSize"
          placeholder="请输入打印尺寸"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['print:print:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['print:print:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['print:print:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['print:print:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="printList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务id" align="center" prop="photoTaskId" />
      <el-table-column label="价格" align="center" prop="money" />
      <el-table-column label="打印状态" align="center" prop="printStatus" />
      <el-table-column label="打印尺寸" align="center" prop="printSize" />
      <el-table-column label="地址" align="center" prop="address" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
            v-hasPermi="['print:print:query']"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewPhotos(scope.row)"
            v-hasPermi="['print:print:query']"
          >查看照片</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['print:print:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['print:print:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改照片打印任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="价格" prop="money">
          <el-input v-model="form.money" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="打印尺寸" prop="printSize">
          <el-input v-model="form.printSize" placeholder="请输入打印尺寸" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看任务关联的照片对话框 -->
    <el-dialog title="任务关联的照片" :visible.sync="photosOpen" width="1000px" append-to-body>
      <div style="margin-bottom: 20px;">
        <el-button type="primary" size="small" @click="handleAddPhotoToTask" v-hasPermi="['print:photo:add']">
          添加照片到任务
        </el-button>
      </div>
      
      <el-table v-loading="photosLoading" :data="photosList">
        <el-table-column label="照片ID" align="center" prop="singlePhotoId" width="100" />
        <el-table-column label="图片预览" align="center" width="150">
          <template slot-scope="scope">
            <el-image 
              style="width: 100px; height: 100px"
              :src="scope.row.imgUrl"
              :preview-src-list="[scope.row.imgUrl]"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="图片地址" align="center" prop="imgUrl" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeletePhoto(scope.row)"
              v-hasPermi="['print:photo:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="photosOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 添加照片到任务对话框 -->
    <el-dialog title="添加照片到任务" :visible.sync="addPhotoOpen" width="600px" append-to-body>
      <el-form ref="photoForm" :model="photoForm" :rules="photoRules" label-width="80px">
        <el-form-item label="图片上传" prop="imgUrl">
          <el-upload
            ref="photoUpload"
            :action="uploadAction"
            :headers="uploadHeaders"
            :data="uploadData"
            :file-list="photoFileList"
            :auto-upload="false"
            :on-change="handlePhotoFileChange"
            :on-remove="handlePhotoFileRemove"
            :before-upload="beforePhotoUpload"
            :limit="1"
            accept="image/*"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
        
        <!-- 图片预览区域 -->
        <el-form-item label="图片预览" v-if="photoPreviewImage">
          <div class="image-preview-container">
            <div class="image-preview-item">
              <el-image 
                :src="photoPreviewImage" 
                :preview-src-list="[photoPreviewImage]"
                fit="cover"
                style="width: 200px; height: 200px; border-radius: 8px;"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPhotoForm" :loading="photoUploadLoading">确 定</el-button>
        <el-button @click="cancelPhoto">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPrint, getPrint, delPrint, addPrint, updatePrint, getPhotosByTaskId } from "@/api/print/print"
import { delPhoto } from "@/api/print/photo"
import { uploadImage } from "@/api/print/upload"

export default {
  name: "Print",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 照片打印任务表格数据
      printList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        money: null,
        printStatus: null,
        printSize: null,
        address: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 照片相关
      photosOpen: false,
      photosLoading: false,
      photosList: [],
      currentTaskId: null,
      addPhotoOpen: false,
      photoUploadLoading: false,
      photoFileList: [],
      photoPreviewImage: null,
      uploadAction: "#",
      uploadHeaders: {},
      uploadData: {},
      photoRules: {
        imgUrl: [{ required: true, message: "请选择图片", trigger: "change" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询照片打印任务列表 */
    getList() {
      this.loading = true
      listPrint(this.queryParams).then(response => {
        this.printList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        photoTaskId: null,
        money: null,
        printStatus: null,
        printSize: null,
        address: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.photoTaskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加照片打印任务"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const photoTaskId = row.photoTaskId || this.ids
      getPrint(photoTaskId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改照片打印任务"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.photoTaskId != null) {
            updatePrint(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPrint(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const photoTaskIds = row.photoTaskId || this.ids
      this.$modal.confirm('是否确认删除照片打印任务编号为"' + photoTaskIds + '"的数据项？').then(function() {
        return delPrint(photoTaskIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('print/print/export', {
        ...this.queryParams
      }, `print_${new Date().getTime()}.xlsx`)
    },
    /** 查看任务关联的照片 */
    handleViewPhotos(row) {
      this.currentTaskId = row.photoTaskId
      this.photosOpen = true
      this.photosLoading = true
      getPhotosByTaskId(row.photoTaskId).then(response => {
        this.photosList = response.data
        this.photosLoading = false
      })
    },
    /** 删除照片 */
    handleDeletePhoto(row) {
      this.$modal.confirm('是否确认删除该照片？').then(function() {
        return delPhoto(row.singlePhotoId)
      }).then(() => {
        this.handleViewPhotos({ photoTaskId: this.currentTaskId })
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 添加照片到任务 */
    handleAddPhotoToTask() {
      this.addPhotoOpen = true
      this.photoFileList = []
      this.photoPreviewImage = null
      this.uploadData.photoTaskId = this.currentTaskId
      this.$nextTick(() => {
        this.$refs.photoUpload.clearFiles()
      })
    },
    /** 图片文件变化 */
    handlePhotoFileChange(file, fileList) {
      this.photoFileList = fileList
      if (fileList.length > 0) {
        this.uploadPhotoFile(file.raw)
      }
    },
    /** 图片文件移除 */
    handlePhotoFileRemove(file, fileList) {
      this.photoFileList = fileList
      this.photoPreviewImage = null
    },
    /** 图片上传前校验 */
    beforePhotoUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
      return false // 阻止自动上传
    },
    /** 上传照片文件 */
    uploadPhotoFile(file) {
      this.photoUploadLoading = true
      uploadImage(file).then(response => {
        if (response.code === 200) {
          this.photoPreviewImage = response.data.originalUrl
          this.$message.success('上传成功')
        } else {
          this.$message.error(response.msg || '上传失败')
        }
      }).catch(error => {
        this.$message.error('上传失败: ' + error.message)
      }).finally(() => {
        this.photoUploadLoading = false
      })
    },
    /** 提交添加照片到任务 */
    submitPhotoForm() {
      if (this.photoPreviewImage === null) {
        this.$message.error('请先上传图片')
        return
      }
      
      // 这里可以调用添加照片到任务的API
      // 暂时关闭对话框
      this.addPhotoOpen = false
      this.$message.success('添加成功')
      // 刷新照片列表
      this.handleViewPhotos({ photoTaskId: this.currentTaskId })
    },
    /** 取消添加照片到任务 */
    cancelPhoto() {
      this.addPhotoOpen = false
      this.photoFileList = []
      this.photoPreviewImage = null
      this.$refs.photoForm.resetFields()
    },
    /** 查看详情 */
    handleViewDetail(row) {
      this.$router.push({ path: '/print/detail', query: { photoTaskId: row.photoTaskId } })
    }
  }
}
</script>

<style scoped>
.image-preview-container {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.image-preview-item {
  text-align: center;
}

.image-preview-label {
  margin-bottom: 10px;
  font-weight: bold;
  color: #606266;
}
</style>
